package com.blackhorse.controller;

import com.alibaba.fastjson.JSON;
import com.blackhorse.domain.Order;
import com.blackhorse.domain.Product;

import com.blackhorse.dubbo.api.ProductService;
import com.blackhorse.service.OrderService;
import lombok.extern.slf4j.Slf4j;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 测试spring-cloud-alibaba-dubbo的controller，使用时打开RestController注解；注意：去掉restTemplate的loadbalanced注解
 */
@Slf4j
@RestController
public class OrderController6 {

    /**
     * 引用dubbo远程服务接口
     */
    @Reference(check = false)
    private ProductService productService;

    @Autowired
    private OrderService orderService;

    /**
     * 用户下单接口
     */
    @RequestMapping("/order/prod/{pid}")
    public Order order(@PathVariable("pid") Integer pid) {
        log.info("订单微服务-下单-开始 pid:{}", pid);

        Product product = productService.findByPid(pid);

        log.info("订单微服务-下单-查询到商品信息 pid:{} product:{}", pid, JSON.toJSONString(product));

        if (product == null) {
            throw new IllegalArgumentException("商品不存在");
        }
        Order order = new Order();
        order.setUid(1);
        order.setUsername("测试用户");
        order.setPid(pid);
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(1);
        orderService.createOrder(order);

        log.info("订单微服务-下单-创建订单成功 order:{}", JSON.toJSONString(order));
        return order;
    }
}
